package com.example.controller;

import com.example.dao.AccountRepository;
import com.example.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-04-22 10:21
 **/
@RestController
@RequestMapping(value = "/account")
public class AccountController {
    @Autowired
    AccountRepository accountRepository;

    /**
     * 查询所有
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<Account> getAll() {
        return accountRepository.findAll();
    }

    /**
     * 根据ID查询
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Account getAccountById(@PathVariable(value = "id") int id) {
        return accountRepository.findById(id);
    }
    /**
     * 更新指定account的信息
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Account putAccount(@PathVariable(value = "id")int id,
                              @RequestParam(value = "name" ,name = "") String  name,
                              @RequestParam(value = "money") double money) {
        Account account = new Account();
        account.setId(id);
        account.setName(name);
        account.setMoney(money);

        return accountRepository.save(account);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public Account postAccount(@RequestParam(value = "name") String name,
                               @RequestParam(value = "money") double money) {
        Account account = new Account();
        account.setName(name);
        account.setMoney(money);

        return accountRepository.save(account);
    }

    /**
     * 删除指定account
     */
    @RequestMapping(value = "/{id}")
    public int deleteAccount(@PathVariable(value = "id") int id) {
        try {
            accountRepository.deleteById(id);
            return 1;
        } catch (Exception e) {
            return -1;
        }

    }
}
